import {useEffect, useRef, useState} from 'react';
import './index.less';
export default function TopRuler(props: {left: number; scale: number}) {
    const rulerRef = useRef<HTMLCanvasElement>(null);
    const [w, setW] = useState(1001);
    const uw = 10;
    const drawLine = (start: number[], end: number[]) => {
        //@ts-ignore
        const {current} = rulerRef;
        //@ts-ignore
        const ctx = current?.getContext('2d');
        const fixWidth = 0.5;
        const [sx, sy] = start;
        const [ex, ey] = end;
        if (ctx) {
            ctx.beginPath();
            ctx.moveTo(sx + fixWidth, sy);
            ctx.lineTo(ex + fixWidth, ey);
            ctx.lineWidth = 1;
            ctx.strokeStyle = '#a1a1a1';
            ctx.closePath();
            ctx.stroke();
        }
    };
    const drawText = (text: number, x: number) => {
        const {current} = rulerRef;
        const ctx = current?.getContext('2d');
        const fixWidth = 0.5;
        if (ctx) {
            ctx.font = '10px';
            ctx.fillStyle = '#fff';
            ctx.fillText(text + '', x + 3.5, 10);
        }
    };
    const draw = () => {
        const {current} = rulerRef;
        const ctx = current?.getContext('2d');
        const w = current?.offsetWidth;
        if (ctx && w) {
            ctx.clearRect(0, 0, w, 20);
            for (let i = 0; i < w - props.left; i += uw) {
                if (i % (10 * uw) === 0) {
                    drawText(i, i + props.left);
                    drawLine([i + props.left, 20], [i + props.left, 0]);
                } else if (i % (5 * uw) === 0) {
                    drawLine([i + props.left, 20], [i + props.left, 8]);
                } else {
                    drawLine([i + props.left, 20], [i + props.left, 14]);
                }
            }
            if (props.left > 0) {
                for (let i = 0; i > 0 - props.left; i -= 10) {
                    if (i % (10 * uw) === 0) {
                        drawText(i, i + props.left);
                        drawLine([i + props.left, 20], [i + props.left, 0]);
                    } else if (i % (5 * uw) === 0) {
                        drawLine([i + props.left, 20], [i + props.left, 8]);
                    } else {
                        drawLine([i + props.left, 20], [i + props.left, 14]);
                    }
                }
            }
        }
    };
    useEffect(() => {
        //@ts-ignore
        const {current} = rulerRef;
        //@ts-ignore
        setW(current.offsetWidth);
        draw();
    }, []);
    useEffect(() => {
        draw();
    }, [props.left, props.scale]);
    return (
        <>
            <div className="top-ruler">
                <canvas ref={rulerRef} width={w} height={20}></canvas>
            </div>
        </>
    );
}
